package com.googlecode.lightest.core

import org.w3c.dom.Document

/**
 * The Lightest customizations to the TestNG XSLT report transforms.
 */
class LightestTransformer extends CustomizedTransformer {
    static final XSL_NS = 'http://www.w3.org/1999/XSL/Transform'

    LightestTransformer() {
        def xsl = getClass().getResourceAsStream('/testng-results.xsl')
        setTransform(xsl);
    }
    
    void customize(Document doc) {
        def head = doc.getElementsByTagName('head').item(0)

        def outputs = doc.getElementsByTagNameNS(XSL_NS, 'output')
        outputs.each { it.setAttribute('indent', 'no') }

        def script = doc.createElement('script')
        script.setAttribute('type', 'text/javascript')
        script.setAttribute('src', 'jquery-1.2.6.min.js')
        head.appendChild(script)

        script = doc.createElement('script')
        script.setAttribute('type', 'text/javascript')
        script.setAttribute('src', 'lightest-base.js')
        head.appendChild(script)
        
        script = doc.createElement('script')
        script.setAttribute('type', 'text/javascript')
        script.setAttribute('src', 'lightest-filenames.js')
        head.appendChild(script)
        
        def object = doc.getElementsByTagName('object').item(0)
        object.setAttribute('width', '450')
        object.setAttribute('height', '150')
        
        // remove the sorting - this causes non-determinism when the order of
        // method runs cannot be distinguished given the time resolution
        def params = doc.getElementsByTagNameNS(XSL_NS, 'with-param')
        for (i in 0..<params.length) {
            def param = params.item(i)
            if (param.getAttribute('name') == 'sortByStartTime') {
                param.setAttribute('select', "'false'")
                break
            }
        }
        
        def outerFrameset = doc.getElementsByTagName('frameset').item(0)
        def innerFrameset = doc.createElement('frameset')
        innerFrameset.setAttribute('rows', '45%, 55%')
        innerFrameset.setAttribute('frameborder', '3')
        
        def contentFrame = outerFrameset.getElementsByTagName('frame').item(1)
        def detailsFrame = doc.createElement('frame')
        detailsFrame.setAttribute('name', 'details')
        
        outerFrameset.removeChild(contentFrame)
        outerFrameset.appendChild(innerFrameset)
        innerFrameset.appendChild(contentFrame)
        innerFrameset.appendChild(detailsFrame)
    }
}